// 右键生成菜单插件
import { createVNode,createApp, render } from "vue"
import menuCom from '@/components/rightClick/index.vue'
let elValue = null
let activeVnode
// 监听右键点击触发的事件
const mountMenu = (e, binding)=> {
    e.preventDefault();
    let instance = createVNode(menuCom,{
      name: '右键菜单',
      // 关闭右键菜单弹窗
      onClose: ()=> {
        render(null, document.querySelector(`#preview-content`))
        elValue.removeEventListener('contextmenu',(e)=> {mountMenu(e, binding)})
      },
      // 删除方法
      onDelete: ()=> {
        // 在自定义指令中向外部传递参数
        activeVnode.props['on:rightClickDeleteHanlder'](binding.value)
      },
      onCopy: () => {
        activeVnode.props['on:rightClickCopyHanlder'](binding.value)
      },
      onChangeHierarchy: (type) => {
        activeVnode.props['on:rightClickChangeHierarchyHanlder'](binding.value,type)
      },
    })
    instance.appContext = app._context
    render(instance, document.querySelector(`#preview-content`))
    // // 计算菜单位置
    // dom的id前加了box
    let dragDom = document.querySelector(`#box${binding.value}`)
    let transformX
    let transformY
    if(dragDom.style.transform!=''){
      let transformValue = dragDom.style.transform.substring(dragDom.style.transform.indexOf('(')+1,dragDom.style.transform.lastIndexOf(')'))
      transformValue = transformValue.split(',')
      transformX = transformValue[0]
      transformY = transformValue[1]
    }
    transformY = transformY? Number(transformY.substring(0,transformY.indexOf('px'))):0
    transformX = transformX? Number(transformX.substring(0,transformX.indexOf('px'))):0
    instance.el.style.position = "absolute";
    instance.el.style.left = `${e.offsetX+parseInt(dragDom.style.left)+Number(transformX)}px`;
    instance.el.style.top = `${e.offsetY+parseInt(dragDom.style.top)+Number(transformY)}px`;
    instance.el.style.zIndex =999;
}
const rightclick = {
    mounted(el, binding,vNode) {
      activeVnode = vNode
      elValue = el
      el.addEventListener("contextmenu", (e)=> {
        let activeCompoent = JSON.parse(sessionStorage.getItem('activeCompoent'))
        if((activeCompoent && activeCompoent.uuid) == binding.value){
          mountMenu(e,binding)
        }
        
      });
    }
  }
export default rightclick